import React, { useEffect, useState, useRef } from 'react';
import { Button, Space, Tag, Avatar, Upload, message, Switch } from 'antd';
import ProList from '@ant-design/pro-list';
import {
  CheckOutlined,
  FileTextOutlined,
  LaptopOutlined,
  ReadOutlined,
  CloseOutlined,
  FilePdfOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import { useRequest } from 'umi';
import moment from 'moment';
import type { UploadProps } from 'antd';
import type { ProFormInstance } from '@ant-design/pro-components';

import {
  ModalForm,
  ProForm,
  ProFormDateRangePicker,
  ProFormSelect,
  ProFormText,
  ProCard,
  ProTable,
} from '@ant-design/pro-components';

const TrainingPlan = ({ stageId }: any) => {
  // console.log(stageId);

  const [tableData, setTableData] = useState([]);
  const uploadRef = useRef<ProFormInstance>();

  const [isShow, setIsShow] = useState(true);

  useEffect(() => {
    getMyStageEducateProg.run();
  }, [stageId]);

  //学生端——获取该阶段培养计划内容
  const getMyStageEducateProg = useRequest(
    () => {
      return {
        url: `http://10.1.40.84:9998/educate/getMyStageEducateProg?stageId=${stageId}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      // manual: true,
      onSuccess: (e) => {
        console.log(e);
      },
      formatResult: (res) => {
        console.log(res);
        let dataTemp: any = [];
        res.data.map((item: any) => {
          let dataObject: any = {
            name: undefined,
            image: undefined,
            done: item.isPass,
            type: item.ruleType,
            subData: item.stuRules,
            stuCount: item.stuCount,
            stime: moment(item.stime).format('YYYY-MM-DD'),
            etime: moment(item.etime).format('YYYY-MM-DD'),
          };
          if (item.ruleType === '论文') {
            dataObject.name = '发表论文数量 大于' + ' ' + item.ruleCount + '篇';
            dataObject.image = <FileTextOutlined style={{ fontSize: 33 }} />;
          }
          if (item.ruleType === '项目') {
            dataObject.name = '完成项目数量 大于' + ' ' + item.ruleCount + '个';
            dataObject.image = <LaptopOutlined style={{ fontSize: 33 }} />;
          }
          if (item.ruleType === '阶段报告') {
            dataObject.name = '完成阶段报告 大于' + ' ' + item.ruleCount + '个';
            dataObject.image = <FilePdfOutlined style={{ fontSize: 33 }} />;
          }
          if (item.ruleType === '参考文献') {
            dataObject.name = '阅读参考文献 大于' + ' ' + item.ruleCount + '篇';
            dataObject.image = <ReadOutlined style={{ fontSize: 33 }} />;
          }
          dataTemp.push(dataObject);
        });
        setTableData(dataTemp[0]?.subData || []);
        return dataTemp;
      },
    },
  );

  // 上传材料文件
  const props: UploadProps = {
    name: 'material',
    action: 'http://10.1.40.84:9998/stuTrain/uploadMaterial',
    headers: {
      Authorization: localStorage.getItem('token') || '',
    },
    maxCount: 1,
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 文件上传成功！`);
        uploadRef.current?.setFieldsValue({
          stuRuleContent: info?.file?.response?.data || '',
        });
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };
  //学生端——学生提交项目或论文
  const uploadStuPaperProj = useRequest(
    (data = {}) => {
      return {
        url: `http://10.1.40.84:9998/educate/uploadStuPaperProj`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
      onSuccess: (e) => {
        getMyStageEducateProg.run();
        console.log(e);
      },
    },
  );

  const columns = [
    {
      title: '名称',
      dataIndex: 'stuRuleName',
      key: 'stuRuleName',
    },
    {
      title: '时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (text: any) => <span>{moment(text).format('YYYY-MM-DD')}</span>,
    },
    {
      title: '是否审核',
      dataIndex: 'isPass',
      key: 'isPass',
      render: (text: any) => {
        if (text === '1') {
          return <Tag color={'processing'}>已审核</Tag>;
        } else {
          return <Tag color={'error'}>未审核</Tag>;
        }
      },
    },
    {
      title: '操作',
      key: '操作',
      render: (text: any, record: any) => (
        <a
          onClick={() => {
            window.open(record.stuRuleContent);
          }}
        >
          查看
        </a>
      ),
    },
  ];

  const SwitchOnChange = (e) => {
    console.log(e);
    setIsShow(!e);
  };

  return (
    <>
      <ProCard
        title={
          <Space>
            <span>阶段任务完成情况</span>
            <Switch
              size="default"
              // defaultChecked
              checkedChildren="开启"
              unCheckedChildren="关闭"
              onChange={SwitchOnChange}
            />
          </Space>
        }
        extra={
          <Space>
            <ModalForm
              key="上传"
              title="上传文件"
              trigger={<Button type="primary">上传文件</Button>}
              autoFocusFirstInput
              modalProps={{
                onCancel: () => console.log('run'),
              }}
              submitTimeout={2000}
              onFinish={async (values) => {
                console.log(values);
                uploadStuPaperProj.run(values);
                return true;
              }}
              grid={true}
              rowProps={{
                gutter: 16,
              }}
              formRef={uploadRef}
            >
              <ProForm.Group>
                <ProFormText
                  required
                  name="stuRuleName"
                  label="文件名称"
                  colProps={{ span: 24 }}
                />
                <ProFormSelect
                  required
                  options={[
                    {
                      value: '论文',
                      label: '论文',
                    },
                    {
                      value: '项目',
                      label: '项目',
                    },
                  ]}
                  name="ruleType"
                  label="文件类型"
                  colProps={{ span: 8 }}
                />
                <Upload {...props}>
                  <Button
                    type="link"
                    style={{ marginTop: 30 }}
                    icon={<UploadOutlined />}
                  >
                    上传
                  </Button>
                </Upload>
                <ProFormText
                  required
                  name="stuRuleContent"
                  label="文件链接"
                  colProps={{ span: 0 }}
                />
              </ProForm.Group>
            </ModalForm>
          </Space>
        }
        // split={'vertical'}
        bordered
        headerBordered
        // collapsible
        // defaultCollapsed
        bodyStyle={{ padding: 0 }}
      >
        <ProList
          size="large"
          // toolBarRender={() => {
          //     return [
          //         <Button key="add" type="primary">
          //             新建
          //         </Button>,
          //     ];
          // }}
          // // style={{fontSize:16}}
          // tableStyle={{fontSize:16}}
          onRow={(record: any) => {
            return {
              // onMouseEnter: () => {
              //     console.log(record);
              // },
              onClick: () => {
                setTableData(record.subData);
              },
            };
          }}
          split={true}
          rowKey="name"
          // headerTitle="阶段任务完成情况"
          // tooltip="基础列表的配置"
          dataSource={getMyStageEducateProg?.data}
          // showActions={true}
          showExtra="hover"
          metas={{
            title: {
              dataIndex: 'name',
              render: (text: any) => (
                <span style={{ fontSize: 18 }}>{text}</span>
              ),
            },
            avatar: {
              dataIndex: 'image',
            },
            // description: {
            //     dataIndex: 'stuCount',
            // },
            subTitle: {
              dataIndex: 'stuCount',
              render: (e, row) => {
                console.log(row);
                return (
                  <div style={{ fontSize: 16 }}>
                    已完成{e}
                    <span style={{ marginLeft: 20 }}>
                      起始时间：{row.stime}至{row.etime}
                    </span>
                  </div>
                );
              },
            },
            actions: {
              dataIndex: 'done',
              render: (text, row) => {
                if (row.done === '完成') {
                  return (
                    <Space>
                      <Tag color="#5BD8A6" style={{ fontSize: 22 }}>
                        {' '}
                        <CheckOutlined />
                      </Tag>
                      {/* <Button
                        type="link"
                        onClick={() => {
                          setTableData(row.subData);
                        }}
                      >
                        查看详情
                      </Button> */}
                    </Space>
                  );
                } else {
                  return (
                    <Space>
                      <Tag color="warning" style={{ fontSize: 22 }}>
                        {' '}
                        <CloseOutlined />
                      </Tag>
                      {/* <Button
                        type="link"
                        onClick={() => {
                          setTableData(row.subData);
                        }}
                      >
                        查看详情
                      </Button> */}
                    </Space>
                  );
                }
              },
            },
          }}
        />
      </ProCard>

      <ProCard hidden={isShow}>
        <ProTable
          size="small"
          columns={columns}
          rowKey={() => Math.random()}
          pagination={{
            showQuickJumper: false,
            pageSize: 3,
            hideOnSinglePage: true,
          }}
          toolBarRender={false}
          search={false}
          dataSource={tableData}
        />
      </ProCard>
    </>
  );
};

export default TrainingPlan;
